package com.af.community.smart.business

import android.os.Bundle
import android.text.SpannableString
import android.text.style.UnderlineSpan
import android.view.View
import cn.jpush.android.api.JPushInterface
import com.af.community.smart.base.*
import com.af.community.smart.utils.*
import com.af.community.smart.viewmodel.LoginViewModel
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class LoginActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setTransparentAndToolbar()
        initTitle(title = "登录")
    }

    override fun getViewModel() = getViewModel<LoginViewModel>()

    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        if (intent.getBooleanExtra("offLine", false)) {
            clearData()
            ActivityStack.screenManager.popAllActivityExcept(this::class.java)
        }

        if (getString("account").isNotBlank()) {
            login_account.setText(getString("account"))
            login_account.setSelection(login_account.text.length)
        }

        // 下划线
        // login_check.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        // login_forget.paint.flags = Paint.UNDERLINE_TEXT_FLAG

        login_check.text = getUnderLineText("没有账号")
        login_forget.text = getUnderLineText("忘记密码")
    }

    override fun doClick(v: View) {
        super.doClick(v)
        when (v.id) {
            R.id.login_check -> startActivity<CheckActivity>()
            R.id.login_forget -> startActivity<PasswordActivity>()
            R.id.bt_login -> {
                val registrationId = JPushInterface.getRegistrationID(baseContext)
                when {
                    login_account.text.isEmpty() -> {
                        login_account.requestFocus()
                        toast("请输入账号")
                        return
                    }
                    login_pwd.text.isEmpty() -> {
                        login_pwd.requestFocus()
                        toast("请输入密码")
                        return
                    }
                    registrationId.isEmpty() -> {
                        toast("网络异常，请稍候再试！")
                        return
                    }
                }

                getViewModel().getLoginData(
                    "account" to login_account.trimString(),
                    "pwd" to login_pwd.textString(),
                    "clientId" to registrationId
                )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            val obj = JSONObject(it)
                            putString("userId", obj.optString("id"))
                            putString("account", obj.optString("account"))
                            putString("userName", obj.optString("userName"))
                            putString("avatar", obj.optString("avatar"))
                            putString("phone", obj.optString("phone"))
                            putString("gridId", obj.optString("gridId"))
                            putString("gridName", obj.optString("attr1"))
                            putString("servicePhone", obj.optString("attr2"))

                            val params = obj.optJSONObject("params") ?: JSONObject()
                            putString("countryName", params.optString("country"))
                            putString("streetName", params.optString("street"))

                            putBoolean("isLogin", true)

                            startActivity<MainActivity>()
                            ActivityStack.screenManager.popActivities(this::class.java)
                        }
                    )
            }
        }
    }

    private fun getUnderLineText(text: String) =
        SpannableString(text).apply {
            setSpan(UnderlineSpan(), 0, text.length, 0)
        }

    private fun clearData() {
        clearBoolean("isLogin")
        clearString("userId", "userName", "avatar", "phone", "gridId", "gridName", "servicePhone")

        //停止及清除极光推送
        JPushInterface.stopPush(applicationContext)
        JPushInterface.clearAllNotifications(applicationContext)
    }

}
